package dk.flashnotes.fff.helpers.pageInspector {
	import dk.flashnotes.fff.FFFBase;	import dk.flashnotes.fff.helpers.EHelpersLayout;	import dk.flashnotes.fff.helpers.HelperBaseUI;	import dk.flashnotes.fff.page.APage;	import dk.flashnotes.fff.page.EPageStates;	import dk.flashnotes.fff.page.PageControl;	import dk.flashnotes.fff.page.PageEvent;	import dk.flashnotes.fff.page.part.APart;	import dk.flashnotes.fff.tree.PageControlEvent;
	import flash.display.Sprite;	import flash.events.Event;	import flash.geom.Point;		

	/**
	 * @author jk
	 */
	public class PageInspector extends HelperBaseUI {

		private var _sSOStoreId : String = "PageInspectorHelper";
		private var _oPageControl : PageControl;
		private var _doCP : APage;
		private var _doPageLabel : PageLabel;

		private var _sprLabelCont : Sprite;

		private var _pPartsOffset : Point = new Point(10, 20);

		public function PageInspector() {
			super(_sSOStoreId);
			setup();
		}

		private function setup() : void {				
			_sprLabelCont = new Sprite();
			addChild(_sprLabelCont);
			
			_sprLabelCont.mouseChildren = false;
			_sprLabelCont.mouseEnabled = false;

			_oPageControl = FFFBase.get_oInstance().oPageControl;
			_oPageControl.addEventListener(PageControlEvent.etNEW_CURRENT_PAGE_SET, onNewPage, false, 0, true);
		}

		private function onNewPage(event : PageControlEvent) : void {
			
			if (_doCP != null) {
				clear();
			}
			
			_doCP = _oPageControl.doCurrentPage;
			
			if (_doCP.sState == EPageStates.READY_TO_OPEN || _doCP.sState == EPageStates.OPENED || _doCP.sState == EPageStates.OPENING) {
				createPartLabels(null);
			} else {
				_doCP.addEventListener(PageEvent.etPAGE_READY_TO_OPEN, createPartLabels, false, 0, true);
			}
			createPageLabel();
		}

		private function createPartLabels(e : Event) : void {
			
			var nCountPosY : Number = _pPartsOffset.y;
			for each (var doPart : APart in _doCP.a_doParts) {
				var doPartLabel : PartLabel = new PartLabel(doPart);
				_sprLabelCont.addChild(doPartLabel);
				
				doPartLabel.x = _pPartsOffset.x;
				doPartLabel.y = nCountPosY;
				nCountPosY += EHelpersLayout.nLINE_SPACE;
			}
			updateBack();
		}

		private function clear() : void {
			
			while(_sprLabelCont.numChildren != 0) {
				IClearable(_sprLabelCont.getChildAt(0)).clear();
				_sprLabelCont.removeChildAt(0);
			}
			
			_doCP.removeEventListener(PageEvent.etPAGE_READY_TO_OPEN, createPartLabels);
			_doCP = null;
		}

		private function createPageLabel() : void {
			
			_doPageLabel = new PageLabel(_doCP);
			_sprLabelCont.addChild(_doPageLabel);
			
			updateBack();
		}
	}
}
